package com.emou.controller.content;

import com.emou.constant.PageCodeEnum;
import com.emou.dto.AdDto;
import com.emou.service.AdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;

/**
 * Created by emou on 2021/1/25.
 */
@Controller
@RequestMapping("/ad")
public class AdController {
    @Autowired
    private AdService adService;
    @RequestMapping
    public String init(ModelMap modelMap){
        AdDto adDto = new AdDto();
        modelMap.addAttribute("list",adService.searchByPage(adDto));
        return "/content/adList";

    }

    @RequestMapping("/search")
    public String search(ModelMap modelMap,AdDto adDto){
        modelMap.addAttribute("list",adService.searchByPage(adDto));
        //jsp页面中的分页标签使用Page类型，就可以通过adDto关联到Page对象
        modelMap.addAttribute("searchParam",adDto);
        return "/content/adList";
    }

    @RequestMapping("/addInit")
    public String addInit() {
        return "/content/adAdd";
    }

    @RequestMapping("/add")
    public String add(AdDto adDto,ModelMap modelMap){
        if(adService.add(adDto)){
            modelMap.addAttribute(PageCodeEnum.KEY,PageCodeEnum.ADD_SUCCESS);
        }else {
            modelMap.addAttribute(PageCodeEnum.KEY,PageCodeEnum.ADD_FAIL);
        }
        return "/content/adAdd";
    }

    @RequestMapping("/toUpdate")
    public String toUpdatePage(ModelMap modelMap,int id) {
        modelMap.addAttribute("list",adService.selectById(id));
        return "/content/adUpdate";
    }

    @RequestMapping("/Update")
    public String modify(ModelMap modelMap, AdDto adDto) throws IOException {
        modelMap.addAttribute("list", adDto);
        if (adService.update(adDto)) {
            modelMap.addAttribute(PageCodeEnum.KEY, PageCodeEnum.UPDATE_SUCCESS);
        } else {
            modelMap.addAttribute(PageCodeEnum.KEY, PageCodeEnum.UPDATE_FAIL);
        }
        return "/content/adUpdate";
    }

    @RequestMapping("/deleteAd")
    public String delete(ModelMap modelMap, int id) {
        if (adService.deleteAd(id)) {
            modelMap.addAttribute(PageCodeEnum.KEY, PageCodeEnum.DELETE_SUCCESS);
        } else {
            modelMap.addAttribute(PageCodeEnum.KEY, PageCodeEnum.DELETE_FAIL);
        }
        return "forward:/ad";
    }
}
